using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StudentVideo.Common.Attributes;
using StudentVideo.Common.Constants;
using StudentVideo.Common.Exceptions;
using StudentVideo.Data;
using StudentVideo.Shared.Dtos.Course;
using StudentVideo.Shared.Enums;

namespace StudentVideo.Controllers;

[ApiController]
[Route("api/[controller]/[action]")]
[RoleAuthorize(RoleEnum.Admin)]
public class CourseController(AppDbContext context): ControllerBase {
   private readonly AppDbContext _context = context;

   /// <summary>
   /// 添加
   /// </summary>
   /// <param name="data"></param>
   /// <returns></returns>
   [HttpPost]
   public async Task Create([FromBody] CourseCreateRequest data) {

      var exists = await _context.Courses.AnyAsync(e => e.Code == data.Code && e.Name == data.Name);

      if (exists)
         throw new HttpException(HttpErrorMessage.COURSE_EXIST);

      var newData = await _context.Courses.AddAsync(new() {
         Name = data.Name,
         Code = data.Code,
         CreateBy = ""
      });

      await _context.SaveChangesAsync();

      return;
   }

   /// <summary>
   /// 删除
   /// </summary>
   /// <param name="data"></param>
   /// <returns></returns>
   [HttpPost]
   public async Task Delete([FromBody] CourseDeleteRequest data) {
      var target = await _context.Courses
         .FirstOrDefaultAsync(e => e.Id == data.Id)
         ?? throw new HttpException(HttpErrorMessage.COURSE_NOT_EXIST);

      _context.Courses.Remove(target);

      await _context.SaveChangesAsync();

      return;
   }

   /// <summary>
   /// 修改
   /// </summary>
   [HttpPost]
   public async Task Edit([FromBody] CourseEditRequest data) {
      var target = await _context.Courses
         .FirstOrDefaultAsync(e => e.Id == data.Id)
         ?? throw new HttpException(HttpErrorMessage.COURSE_NOT_EXIST);

      target.Enable = data?.Status ?? target.Enable;
      target.Code = data?.Code ?? target.Code;
      target.Name = data?.Name ?? target.Name;

      await _context.SaveChangesAsync();

      return;
   }

   /// <summary>
   /// 所有
   /// </summary>
   /// <returns></returns>
   [HttpPost]
   public async Task<List<CourseSearchResult>> Search() {
      var values = await _context.Courses
         .Where(e => e.Enable == true)
         .Select(e => new CourseSearchResult {
            Id = e.Id,
            Name = e.Name,
            Code = e.Code,
         }).ToListAsync();

      return values;
   }
}
